package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bean.Seat;
import com.bean.SeatLog;
import com.dao.SeatDao;
import com.service.SeatLogService;
import com.service.SeatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SeatServiceImpl extends ServiceImpl<SeatDao, Seat> implements SeatService {

    @Autowired
    SeatLogService seatLogService;
    Logger logger = LoggerFactory.getLogger(SeatServiceImpl.class);

    @Override
    public boolean exit(SeatLog seatUser) {
        Seat seat = new Seat();
        seat.setUserName("null");
        seat.setStatus("no");
        boolean update = this.update(seat, new LambdaUpdateWrapper<Seat>().eq(Seat::getUserName, seatUser.getUserName()));
        logger.info("用户名:{} 座位号: {} 离开座位成功", seatUser.getUserName(), seatUser.getSeatName());
        if (!update) {
            seatUser.setStatus(seatUser.getStatus() + "--> exitError");
        } else {
            seatUser.setStatus(seatUser.getStatus() + "--> no");
        }
        Date endTime = new Date();
        //加一秒防止开始结束同时点击
        Long useTime = ((endTime.getTime() + 1000) - seatUser.getBeginTime().getTime()) / (1000 * 60);
        seatUser.setEndTime(endTime);
        seatUser.setUseTime(useTime);
        try {
            seatLogService.updateById(seatUser);
        } catch (Exception e) {
            logger.error("用户名:{} 退出失败已成功记录,全部信息{}", seatUser.getUserName(), seatUser);
        }
        logger.info("用户名:{} 座位号: {} 退出记录已成功记录到数据库", seatUser.getUserName(), seatUser.getSeatName());
        return update;
    }

    @Override
    @Transactional
    public SeatLog selected(String data, String userName) {
        Seat seat = new Seat();
        seat.setUserName(userName);
        seat.setStatus("occupied");
        seat.setBeginTime(new Date());
        boolean update = this.update(seat, new LambdaUpdateWrapper<Seat>().eq(Seat::getSeatName, data).eq(Seat::getStatus, "no"));
        logger.info("用户名:{} 座位号: {} 选座成功", userName, data);
        SeatLog seatLog = new SeatLog();
        BeanUtils.copyProperties(seat, seatLog);
        seatLog.setSeatName(data);
        seatLog.setBeginTime(seat.getBeginTime());
        if (!update) {
            seatLog.setStatus("addError");
            logger.error("用户名:{} 座位号: {} 选座失败," + userName, data);
        }
        seatLogService.save(seatLog);
        logger.info("用户名:{} 座位号: {} 选座记录已成功记录到数据库", userName, data);
        if (update) {
            return seatLog;
        } else {
            return null;
        }
    }
}

